#!/usr/bin/env python
# -*- coding:utf-8 -*-
import time

from rich.console import Console
from rich.table import Column, Table
from collections import OrderedDict


class Command:
    def __init__(self, func, title):
        self.func = func
        self.title = title


class _CliTool:
    def __init__(self):
        self.cmd_tbl = OrderedDict()
        self.console = Console(
            width=60,
            force_terminal=True,
            # file=io.StringIO(),
            legacy_windows=False,
        )
        self.count = 0
        self.free_type = False
        self.table = Table(show_header=True, header_style="bold magenta")
        self.table.add_column("id", style="dim", justify="center")
        self.table.add_column("指令(固定模式)", width=20, justify="left")
        self.table.add_row("0", "[red]切换模式[/red]")
        self.cmd_tbl["0"] = Command(self.change_model, "切换模式")

    def add_cmd(self, cmd: Command):
        self.table.add_row(str(len(self.cmd_tbl)), f"[red]{cmd.title}[/red]")
        self.cmd_tbl[str(len(self.cmd_tbl))] = cmd

    def show_cmd(self):
        while 1:
            self.console.print(self.table)
            _cmd_id = input("请输入指令：")
            if _cmd_id not in self.cmd_tbl:
                print("你输入的指令不存在！")
            else:
                self.cmd_tbl[_cmd_id].func(self.free_type)
                print('运行时间 : {}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))))

    def change_model(self, free_type):
        self.count += 1
        if self.count % 2 == 0:
            self.table.columns[1].header = "指令(固定模式)"
            self.free_type = False
        else:
            self.table.columns[1].header = "指令(自由模式)"
            self.free_type = True


class Tool:
    cli = _CliTool()

    @classmethod
    def add(cls, name):
        def wrap(func):
            cls.cli.add_cmd(Command(func, name))
            return func

        return wrap

    @classmethod
    def run(cls):
        cls.cli.show_cmd()
